<template>
  <div>
    <div class="update-token-container">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>设备信息管理</span>
          </div>
        </template>

        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          class="update-token-form"
        >
          <el-form-item label="主设备名称" prop="main_device">
            <el-input
              v-model="form.main_device"
              placeholder="请输入主设备名称"
              clearable
            />
          </el-form-item>

          <el-form-item label="主设备IP" prop="main_device_ip">
            <el-input
              v-model="form.main_device_ip"
              placeholder="请输入主设备IP"
              clearable
            >
              <template #append>
                <el-button
                  @click="openIframe(form.main_device_ip, 'main')"
                  :disabled="!form.main_device_ip"
                  type="primary"
                  size="small"
                >
                  打开
                </el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="子设备名称" prop="sub_device">
            <el-input
              v-model="form.sub_device"
              placeholder="请输入子设备名称"
              clearable
            />
          </el-form-item>

          <el-form-item label="子设备IP" prop="sub_device_ip">
            <el-input
              v-model="form.sub_device_ip"
              placeholder="请输入子设备IP"
              clearable
            >
              <template #append>
                <el-button
                  @click="openIframe(form.sub_device_ip, 'sub')"
                  :disabled="!form.sub_device_ip"
                  type="primary"
                  size="small"
                >
                  打开
                </el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="主设备Token" prop="main_device_token">
            <el-input
              v-model="form.main_device_token"
              type="textarea"
              :rows="4"
              placeholder="请输入主设备Token"
              clearable
            />
          </el-form-item>

          <el-form-item label="子设备Token" prop="sub_device_token">
            <el-input
              v-model="form.sub_device_token"
              type="textarea"
              :rows="4"
              placeholder="请输入子设备Token"
              clearable
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleUpdate" :loading="loading">
              更新设备信息
            </el-button>
            <el-button @click="handleReset">重置</el-button>
            <!-- <el-button @click="handleQuery" :loading="queryLoading">
            查询当前信息
          </el-button> -->
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <!-- iframe显示区域 -->
    <el-card v-if="currentIframe.url" class="iframe-card">
      <template #header>
        <div class="card-header">
          <span>{{ currentIframe.title }}</span>
          <el-button @click="closeIframe" type="danger" size="small"
            >关闭</el-button
          >
        </div>
      </template>
      <div class="iframe-container">
        <iframe
          :src="currentIframe.url"
          frameborder="0"
          width="100%"
          height="90vh"
          @load="handleIframeLoad"
          @error="handleIframeError"
        ></iframe>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { updateTokenWithParamsApi, updateTokenApi } from "@/api/user";

// 表单引用
const formRef = ref();

// 加载状态
const loading = ref(false);
const queryLoading = ref(false);

// 表单数据
const form = reactive({
  main_device: "",
  main_device_ip: "",
  sub_device: "",
  sub_device_ip: "",
  main_device_token: "",
  sub_device_token: "",
});

// 查询结果
const queryResult = ref(null);

// iframe相关
const currentIframe = reactive({
  url: "",
  title: "",
});

// 表单验证规则
const rules = {
  main_device: [
    { required: true, message: "请输入主设备名称", trigger: "blur" },
  ],
  main_device_ip: [
    { required: true, message: "请输入主设备IP", trigger: "blur" },
  ],
  sub_device: [
    { required: true, message: "请输入子设备名称", trigger: "blur" },
  ],
  sub_device_ip: [
    { required: true, message: "请输入子设备IP", trigger: "blur" },
  ],
  main_device_token: [
    { required: true, message: "请输入主设备Token", trigger: "blur" },
  ],
  sub_device_token: [
    { required: true, message: "请输入子设备Token", trigger: "blur" },
  ],
};

// 页面加载时自动查询
onMounted(() => {
  handleQuery();
});

// 更新设备信息
const handleUpdate = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    loading.value = true;

    const response = await updateTokenWithParamsApi({
      ...queryResult.value,
      main_device: form.main_device,
      main_device_ip: form.main_device_ip,
      sub_device: form.sub_device,
      sub_device_ip: form.sub_device_ip,
      main_device_token: form.main_device_token,
      sub_device_token: form.sub_device_token,
    });

    if (response && response.data) {
      // 更新localStorage中的token
      if (response.data.main_device_token) {
        localStorage.setItem("token175", response.data.main_device_token);
      }
      if (response.data.sub_device_token) {
        localStorage.setItem("token43", response.data.sub_device_token);
      }

      ElMessage.success("设备信息更新成功");

      // 更新查询结果
      queryResult.value = response.data;
    } else {
      ElMessage.warning("更新失败，未获取到有效数据");
    }
  } catch (error) {
    console.error("更新设备信息失败:", error);
    ElMessage.error("更新设备信息失败");
  } finally {
    loading.value = false;
  }
};

// 查询当前设备信息
const handleQuery = async () => {
  try {
    queryLoading.value = true;

    const response = await updateTokenApi();

    if (
      response &&
      response.data &&
      Array.isArray(response.data) &&
      response.data.length > 0
    ) {
      queryResult.value = response.data[0];
      console.log(queryResult.value, "queryResult.value");

      // 自动填充表单
      form.main_device = queryResult.value.main_device || "";
      form.main_device_ip = queryResult.value.main_device_ip || "";
      form.sub_device = queryResult.value.sub_device || "";
      form.sub_device_ip = queryResult.value.sub_device_ip || "";
      form.main_device_token = queryResult.value.main_device_token || "";
      form.sub_device_token = queryResult.value.sub_device_token || "";

      ElMessage.success("查询成功");
    } else {
      ElMessage.warning("查询失败，未获取到有效数据");
    }
  } catch (error) {
    console.error("查询设备信息失败:", error);
    ElMessage.error("查询设备信息失败");
  } finally {
    queryLoading.value = false;
  }
};

// 重置表单
const handleReset = () => {
  if (!formRef.value) return;

  formRef.value.resetFields();
  queryResult.value = null;

  // 清空表单数据
  form.main_device = "";
  form.main_device_ip = "";
  form.sub_device = "";
  form.sub_device_ip = "";
  form.main_device_token = "";
  form.sub_device_token = "";
};

// 打开iframe嵌入
const openIframe = (ip: string, type: string) => {
  if (!ip) {
    ElMessage.warning("请先输入IP地址");
    return;
  }

  // 构建URL，添加8082端口
  const url = `http://${ip}:8082`;
  const title = type === "main" ? `主设备 - ${ip}:8082` : `子设备 - ${ip}:8082`;

  // 设置iframe数据
  currentIframe.url = url;
  currentIframe.title = title;

  ElMessage.success(`正在加载${title}`);
};

// 关闭iframe
const closeIframe = () => {
  currentIframe.url = "";
  currentIframe.title = "";
};

// iframe加载完成
const handleIframeLoad = () => {
  console.log("iframe加载完成");
};

// iframe加载错误
const handleIframeError = () => {
  ElMessage.error("页面加载失败，请检查IP地址是否正确");
};
</script>

<style scoped lang="scss">
.update-token-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.box-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 18px;
    font-weight: bold;
  }
}

.update-token-form {
  margin-top: 20px;
}

.query-result {
  margin-top: 30px;

  .el-descriptions {
    margin-top: 10px;
  }
}

:deep(.el-descriptions__label) {
  font-weight: bold;
}

:deep(.el-descriptions__content) {
  word-break: break-all;
}

.iframe-card {
  margin-top: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 16px;
    font-weight: bold;
  }
}

.iframe-container {
  width: 90%;
  height: 90vh;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;

  iframe {
    border: none;
    width: 100%;
    height: 100%;
  }
}
</style>
